package work.darren.webchat.websocket;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.var;
import work.darren.webchat.bean.ChatMsg;
import work.darren.webchat.bean.ChatType;
import work.darren.webchat.bean.ChatUser;
import work.darren.webchat.util.HashUtil;
import work.darren.webchat.util.HttpRequest;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 * @author darren
 * @date 2016年7月15日 下午2:42:15
*/
@ServerEndpoint("/webchat")
public class WebChat{
	
	public static final Map<String, ChatUser> allUser = new ConcurrentHashMap<>();
	
	@OnOpen
	public void onOpen(Session session){
		try {
			ChatMsg msg = new ChatMsg(HashUtil.MD5(session.getId()));
			msg.setType(ChatType.login);
			session.getBasicRemote().sendText(JSON.toJSONString(msg));
		} catch (IOException e) {
			System.out.println(e.getMessage());
		}
	}
	
	@OnMessage
	public void onMessage(Session session,String msgjson){
		JSONObject json = JSON.parseObject(msgjson);
		ChatMsg msg = new ChatMsg(HashUtil.MD5(session.getId()));
		String action = json.getString("action"),name=xss(json.getString("usr"));
		msg.setName(name);
		if("login".equals(action)){
			allUser.put(HashUtil.MD5(session.getId()),new ChatUser(name,session));
			msg.setMsg(name+"加入群聊，当前在线"+allUser.size()+"人");
			msg.setType(ChatType.notify);
		}else if("talk".equals(action)){
			msg.setMsg(xss(json.getString("msg")).replaceAll("\n", "<br>"));
			msg.setType(ChatType.msg);
		}else if("img".equals(action)){
			msg.setMsg(xss(json.getString("msg")));
			msg.setType(ChatType.img);
		}else if("location".equals(action)){
			JSONObject bd = JSON.parseObject(HttpRequest.get("http://api.map.baidu.com/geoconv/v1/").put("coords",json.getString("location")).put("ak", "5ad20b207f849311812ca7946f9feb1f").send());
			if(bd.getInteger("status")==0){
				JSONArray result = bd.getJSONArray("result");
				if(result!=null&&result.size()>0){
					bd = result.getJSONObject(0);
					msg.setType(ChatType.location);
					msg.setMsg(bd.get("x")+","+bd.get("y"));
					sendMsg(JSON.toJSONString(msg));
				}
			}
			return;
		}else if("music".equals(action)){
			msg.setType(ChatType.music);
			msg.setMsg(json.getString("msg"));
			msg.setUrl(json.getString("url"));
		}
		sendMsg(JSON.toJSONString(msg));
	}
	@OnError
	public void onError(Session session,Throwable t){
		System.out.println(t.getMessage());
	}
	
	@OnClose
	public void onClose(Session session){
		String name = allUser.get(HashUtil.MD5(session.getId())).getName();
		allUser.remove(HashUtil.MD5(session.getId()));
		ChatMsg msg = new ChatMsg();
		msg.setMsg(name+"离开群聊，当前在线"+allUser.size()+"人");
		msg.setType(ChatType.notify);
		sendMsg(JSON.toJSONString(msg));
	}
	
	/**
	 * 公共发消息方法
	 * @param msg
	 */
	private void sendMsg(String msg){
		allUser.forEach((k,v)->{
			try {
				if(v.getSession().isOpen()) {
					v.getSession().getBasicRemote().sendText(msg);
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		});
	}

	/**
	 * 公共防止消息带有html标签恶意注入的方法
	 * @param msg
	 */
	private String xss(String msg){
		return msg.replaceAll("<", "&lt;").replaceAll(">", "&gt;");
	}
}
